import Mock from 'mockjs';

const namespace = 'task-list';

let total = 37;

const object = Mock.mock({
  [`dataSource|${total}`]: [
    {
      id: '@increment()',
      name: '@ctitle()',
      rawVersion: '@id()',
      newVersion: '@id()',
      username: '@word(9)',
      dateCreated: '2019-12-10 23:13:00',
    },
  ],
  total,
});

let baseDataSource = object.dataSource;

export default {
  [`GET /api/${namespace}s`]: (req, res) => {
    // console.log('MOCK-GET', req.query);

    let dataSource = baseDataSource;

    /**
     * 检索
     */
    if (req.query.name) {
      dataSource = dataSource.filter(item => item.name.indexOf(req.query.name) !== -1);
    }
    if (req.query.username) {
      dataSource = dataSource.filter(item => item.username.indexOf(req.query.username) !== -1);
    }

    /**
     * 分页
     */
    let current = parseInt(req.query.current, 10);
    const pageSize = parseInt(req.query.pageSize, 10);
    let offset = (current - 1) * pageSize;

    total = dataSource.length; // 当前数据总量
    if (offset >= total) {
      // 分页-错误数据修正
      current = parseInt(total / pageSize, 10);
      current = current > 1 ? current : 1;
      offset = (current - 1) * pageSize;
    }

    dataSource = dataSource.filter((item, index) => index >= offset && index < offset + pageSize);

    res.send({
      dataSource: [...dataSource],
      total,
    });
  },

  [`POST /api/${namespace}s`]: (req, res) => {
    // console.log('MOCK-POST', req.body);

    const instance = {
      ...req.body,
      ...{
        id: Mock.mock('@increment()'),
      },
    };

    baseDataSource.unshift(instance);
    res.send({ message: 'Ok' });
  },

  [`DELETE /api/${namespace}s/:id`]: (req, res) => {
    // console.log('MOCK-DELETE', req.query);

    baseDataSource = baseDataSource.filter(item => parseInt(req.query.id, 10) !== item.id);

    res.send({ message: 'Ok' });
  },

  [`PUT /api/${namespace}s/:id`]: (req, res) => {
    // console.log('MOCK-PUT', req.body);

    baseDataSource = baseDataSource.map(item => {
      if (parseInt(req.body.id, 10) === item.id) {
        Object.assign(item, req.body);
        return item;
      }
      return item;
    });

    res.send({ message: 'Ok' });
  },
};
